<template>
  <div class="topic-container">
    <div class="main-content">

      <div class="return">
        <img src="@/assets/return.png" alt="返回" @click="returnToPreviousPage">
        <span class="returnfont" @click="returnToPreviousPage">&ensp;返回&emsp;&emsp;</span>
        <span @click="returnToPreviousPage">互动问答&ensp;</span>
        <span>></span>
        <span class="returnfont">&ensp;话题详情</span>
      </div>


      <!-- Topic Header with Gray Background -->
      <div class="topic-header">
        <h3>话题{{ topictitle }}</h3>
      </div>

      <!-- 回复数量和排序选项 -->
      <div class="reply-info">
        <p>共{{ replies.length }} 条回复</p>
        <div class="sorting-options">
          <span>排序方式：</span>
          <select v-model="sortBy" @change="sortReplies">
            <option value="latest">最新</option>
            <option value="oldest">最旧</option>
          </select>
        </div>
      </div>

      <!-- 分隔线 -->
      <hr class="divider">



      <div>
        <!-- 回复列表 -->
        <div class="replies">
          <div v-for="reply in displayedReplies" :key="reply.id" class="reply">
            <p class="reply-contents">{{ reply.content }}</p>
            <div class="reply-meta">
              <p class="reply-author">{{ reply.author }}</p>
              <p class="reply-timestamp">{{ formatDateTime(reply.timestamp) }}</p>
              <!-- <p class="reply-delete" @click="showConfirmModal(reply.id)">删除</p> -->
               <!-- 仅当回复作者是当前用户时显示删除按钮 -->
               <!-- <p v-if="reply.author === currentUser" class="reply-delete" @click="showConfirmModal(reply.id)">删除</p> -->
               <p v-if="reply.authorId == currentUserId" class="reply-delete"  @click="showConfirmModal(reply.id)">删除</p>
            </div>
            <hr class="reply-divider">
          </div>
        </div>

        <!-- 改进后的确认删除模态框 -->
        <div v-if="replyIdToDelete !== null" class="modal-overlay">
          <div class="modal">
            <div class="modal-header">
              <h3>确认删除</h3>
              <button class="modal-close-btn" @click="cancelDelete">×</button>
            </div>
            <div class="modal-body">
              <p>您确定要删除此回复吗？</p>
            </div>
            <div class="modal-footer">
              <button class="modal-cancel-btn" @click="cancelDelete">取消</button>
              <button class="modal-confirm-btn" @click="confirmDelete(replyIdToDelete)">删除</button>
            </div>
          </div>
        </div>

      </div>
      <!-- 分页 -->
      <div class="pagination">
        <button class="page-button" :disabled="currentPage === 1" @click="goToPage(currentPage - 1)">上一页</button>
        <span v-for="pageNumber in totalPages" :key="pageNumber">
          <button class="page-number" :class="{ active: pageNumber === currentPage }" @click="goToPage(pageNumber)">
            {{ pageNumber }}
          </button>
        </span>
        <button class="page-button" :disabled="currentPage === totalPages"
          @click="goToPage(currentPage + 1)">下一页</button>
      </div>

      <!-- Reply Input Box -->
      <div class="reply-input">
        <textarea v-model="newReplyContent" placeholder="请输入发表内容"></textarea> <!-- Textarea style -->
        <button @click="addReply">发表回复</button>
      </div>
    </div> <!-- main-content -->

    <div class="sidebar">
      <div class="progress-section">
        <img :src="avatar" alt="avatar" class="avatar">
        <h3>发帖人</h3>
        <span>{{ teacher }}</span>
        <span class="role1">老师{{ tearole }}</span>
      </div>
    </div>

  </div>
</template>

<script>
import axios from 'axios';
export default {
  data() {
    return {
      currentUserId: localStorage.getItem("userid") || '',
      topicId: null,
      topictitle: '',
      replies: [], // Placeholder for replies data
      sortBy: 'latest',
      currentPage: 1,
      repliesPerPage: 5,
      newReplyContent: '',
      fromPath: '', // 保存来源路径
      fromTab: '',// 保存来源页面的 tab 信息,
      teacher: '',
      tearole: '',
      avatar:'',
      replyIdToDelete: null,
    };
  },
  computed: {

    totalPages() {
      return Math.ceil(this.replies.length / this.repliesPerPage);
    },

    displayedReplies() {
      const sortedReplies = this.sortRepliesByMethod([...this.replies]);
      const startIndex = (this.currentPage - 1) * this.repliesPerPage;
      return sortedReplies.slice(startIndex, startIndex + this.repliesPerPage);
    }
  },
  methods: {
    /////明天记得看看要不要加个topicId
    async addReply() {
      try {
        //   // 获取当前用户ID
        this.currentUserId = localStorage.getItem("userid");
        //const userid = localStorage.getItem("userid");
        const response = await axios.post(`http://8.138.12.59:1999/post/${this.topicId}/comment/add`, {
          content: this.newReplyContent,
          upvote: 1,
          downvote: 1,
          user_id:this.currentUserId,
          father_comment: 1
        });

        if (response.data.status === 1) {
          // 成功添加评论
          const newComment = {
            id: response.data.data.comment_id,
            content: response.data.data.content,
            author: response.data.data.user.username,
            authorId: response.data.data.user_id, // 假设接口返回了用户ID
            timestamp: response.data.data.update_time
          };
         
          this.replies.push(newComment); // 确保视图更新
          // 打印 newComment 对象
          console.log('新评论:', newComment);

          // 清空新回复的表单数据
          this.newReplyContent = '';

        } else {
          // 添加评论失败
      if (response.data.msg === '评论内包含敏感词，请修改') {
        // 弹窗提示用户评论包含敏感词，请修改
        alert('评论包含敏感词，请修改');
      } else {
        console.error('刷新回复', response.data.msg);
        console.log('完整的后端返回数据结构：', response.data);
        console.log('新回复内容：', this.newReplyContent);
      }
        }

      } catch (error) {
        console.error('发表回复失败', error);
        console.log('新回复内容：', this.newReplyContent);
      }
    },
    async fetchTopicDetails(topicId) {
      try {
      //   // 获取当前用户ID
        this.currentUserId = localStorage.getItem("userid");
        const response = await axios.get(`http://8.138.12.59:1999/post/hot`);//这里应该改为hot
        const topics = response.data.data;

        // 找到对应id的话题
        const topic = topics.find(topic => topic.post_id === topicId);
        if (topic) {
          this.topictitle = topic.content; // 设置话题标题为内容
          this.teacher = topic.user_name; // 设置发帖人
          this.avatar = topic.img_url; // 设置发帖人
          // this.tearole = topic.publisher_id; // 设置发帖人身份

          //this.replies = []; // 清空回复列表，根据实际接口数据处理

          // 获取特定话题的回复信息
          const response = await axios.get(`http://8.138.12.59:1999/post/${topicId}/comment`);
          const comments = response.data.data;

          // 更新回复列表
          this.replies = comments.map(comment => ({
            id: comment.comment_id,
            content: comment.content,
            author: comment.username,
            authorId: comment.user_id, // 假设接口返回了用户ID
            timestamp: comment.update_time
          }));

        } else {
          console.error(`找不到id为${topicId}的话题`);
        }
      } catch (error) {
        console.error('获取话题详情失败', error);
      }
    },
    returnToPreviousPage() {
      // 在这里实现返回上一页的逻辑，可以使用路由或者简单的浏览器历史记录来实现
      // 例如，使用 Vue Router：
      // this.$router.go(-1);
      // 如果存在 fromPath，说明有记录的前一页路径
      // 恢复之前的 tab 状态
      // 返回到之前页面的方法
      console.log('Returning to previous page...');
      console.log('fromPath:', this.fromPath);
      console.log('fromTab:', this.fromTab);

      if (this.fromPath) {
        console.log('Navigating to:', { path: this.fromPath, query: { tab: this.fromTab } });
        this.$router.push({
          path: '/questions',
          query: { tab: this.fromTab }
        });
      } else {
        console.log('No fromPath found, going back one step in history.');
        this.$router.go(-1);
      }
    },

    sortRepliesByMethod(replies) {
      switch (this.sortBy) {
        case 'oldest':
          return replies.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
        case 'latest':
        default:
          return replies.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
      }
    },

    goToPage(pageNumber) {
      if (pageNumber >= 1 && pageNumber <= this.totalPages) {
        this.currentPage = pageNumber;
      }
    },

    showConfirmModal(replyId) {
      this.replyIdToDelete = replyId;
      // this.confirmModalVisible = true;
    },
    cancelDelete() {
      this.replyIdToDelete = null;
    },
    confirmDelete(replyId) {
      const url = `http://8.138.12.59:1999/post/${this.topicId}/comment`;

      axios.delete(url, {
        data: {
          comment_id: replyId
        }
      })
        .then(response => {
          // 处理成功响应
          console.log(response.data);
          // 更新界面上的回复列表
          const index = this.replies.findIndex(reply => reply.id === replyId);
          if (index !== -1) {
            this.replies.splice(index, 1); // 从数组中移除被删除的回复对象
          } else {
            console.error('无法找到要删除的回复对象');
          }
          this.replyIdToDelete = null; // 隐藏模态框
        })
        .catch(error => {
          // 处理错误
          console.error('删除评论失败:', error);
        });
    },
    //   deleteReply(replyId) {
    //   // 发送DELETE请求
    //   const url = `http://10.33.68.69:8080/post/${this.topicId}/comment`;

    //   axios.delete(url, {
    //     data: {
    //       comment_id: replyId
    //     }
    //   })
    //   .then(response => {
    //     // 处理成功响应
    //     console.log(response.data);
    //     // 如果需要更新界面上的回复列表，可以在这里进行相应操作
    //    // 更新界面上的回复列表
    //     // 假设你的回复列表是存储在 this.replies 中
    //     const index = this.replies.findIndex(reply => reply.id === replyId);
    //     if (index !== -1) {
    //       // 从数组中移除被删除的回复对象
    //       this.replies.splice(index, 1);
    //     } else {
    //       console.error('无法找到要删除的回复对象');
    //     }
    //   })
    //   .catch(error => {
    //     // 处理错误
    //     console.error('删除评论失败:', error);
    //   });
    // },

    sortReplies() {
      this.replies = this.sortRepliesByMethod(this.replies);
      this.currentPage = 1;
    },
    formatDateTime(datetime) {
      if (!datetime) return '';
      const date = new Date(datetime);
      const year = date.getFullYear();
      const month = ('0' + (date.getMonth() + 1)).slice(-2);
      const day = ('0' + date.getDate()).slice(-2);
      const hours = ('0' + date.getHours()).slice(-2);
      const minutes = ('0' + date.getMinutes()).slice(-2);
      const seconds = ('0' + date.getSeconds()).slice(-2);
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
  },
  mounted() {
    this.topicId = parseInt(this.$route.params.id); // 获取路由中的话题id参数
    this.fetchTopicDetails(this.topicId); // 根据话题id获取话题详情和回复列表
    this.fromPath = this.$route.path; // 当前路径
    this.fromTab = this.$route.query.tab;// 当前选项卡状态
  },
 
};
</script>

<style scoped>
.topic-container {
  display: flex;
  background-color: #f9f9f9;
  padding: 20px 50px 20px 50px;
  margin: 0 150px 0 150px;
}

.main-content {
  flex: 3;
  padding: 20px;
  background-color: #ffffff;
  margin-right: 20px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-left: 0;
}

.return {
  cursor: pointer;
  text-align: left;
  margin-bottom: 10px;
}

.returnfont {
  color: rgb(59, 150, 255);
}

.topic-header {
  background-color: #f0f0f0;
  padding: 5px 20px 5px 20px;
  border-radius: 5px;
  text-align: left;
}

.reply-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 5px;
}

.reply-contents {
  margin-top: 30px;
  margin-bottom: 5px; /* 调整内容底部边距 */
  text-align: left;
  color: #000;
}

p {
    padding-bottom: initial !important;
}

.reply-meta {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  /* 左对齐 */
 
}

.reply-author,
.reply-timestamp {
  margin-right: 10px;
  /* 调整作者和时间戳之间的间距 */
}

.reply-timestamp {
  margin-right: 10px;
  /* 调整作者和时间戳之间的间距 */
}

.reply-delete {
  margin-top: 8px;
  margin-left: auto;
  margin-right: 100px;
  font-size: 14px;
  color: initial;
  /* 初始颜色 */
  cursor: pointer;
  /* 鼠标指针样式为指针 */
}

.reply-delete:hover {
  color: rgb(59, 150, 255);
  /* 鼠标悬浮时颜色变为蓝色 */
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  /* 半透明黑色背景 */
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  /* 使模态框在顶层显示 */
}

.modal {
  background-color: #fff;
  width: 400px;
  max-width: 90%;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.modal-header h3 {
  margin: 0;
  font-size: 1.25rem;
}

.modal-close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  outline: none;
}

.modal-body {
  margin-bottom: 20px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
}

.modal-footer button {
  padding: 10px 20px;
  margin-left: 10px;
  border-radius: 4px;
  cursor: pointer;
  border: none;
  outline: none;
}

.modal-cancel-btn {
  background-color: #ccc;
  color: #333;
}

.modal-confirm-btn {
  background-color: #f44336;
  color: white;
}

.sorting-options {
  display: flex;
  align-items: center;
}

.divider {
  border: none;
  border-top: 1px solid #ccc;
  margin: 20px 0;
}

.replies {
  margin-top: 20px;
}

.reply {
  margin-bottom: 15px;
}

.reply-divider {
  border: none;
  border-top: 1px dashed #ccc;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

.page-button {
  background-color: #fff;
  border: 1px solid #007bff;
  color: #000;
  padding: 5px 10px;
  margin: 0 5px;
  cursor: pointer;
}

.page-button:hover {
  background-color: #007bff;
  color: #fff;
}

.page-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.page-number {
  background-color: #fff;
  border: 1px solid #007bff;
  color: #000;
  padding: 5px 10px;
  margin: 0 5px;
  cursor: pointer;
}

.page-number.active {
  background-color: #007bff;
  color: #fff;
}

.reply-input {
  margin-top: 20px;
}

.reply-input textarea {
  width: 98%;
  height: 150px;
  /* 设置合适的高度 */
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 3px;
  resize: none;
}

.reply-input button {
  background-color: #007bff;
  color: #fff;
  border: none;
  padding: 8px 15px;
  border-radius: 3px;
  margin-left: 200px;
  float: right;
  margin-top: 10px;
  cursor: pointer;

}

.reply-input button:hover {
  background-color: #0056b3;
}

.related-courses {
  margin-bottom: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  padding: 15px;
}

.sidebar {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 10px;
}


.progress-section {
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.role1 {
  background-color: #007bff;
  color: white;
  padding: 2px 4px;
  border-radius: 4px;
  margin-left: 5px;
}
</style>
